package com.zhuky.rabbit.task;

import com.alibaba.fastjson.JSON;
import com.zhuky.rabbit.constant.Constants;
import com.zhuky.rabbit.mapper.MessageLogMapper;
import com.zhuky.rabbit.model.MessageLog;
import com.zhuky.rabbit.model.Order;
import com.zhuky.rabbit.producer.RabbitOrderSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class RetryMessageTask {
    @Autowired
    private RabbitOrderSender rabbitOrderSender;

    @Resource
    private MessageLogMapper messageLogMapper;
    @Scheduled(initialDelay = 3000, fixedDelay = 10000)
    public void reSend(){
        log.info("--------------定时任务开始----------------");
        List<MessageLog> messageLogList = messageLogMapper.queryStatusAndTimeoutMessage();
        log.info("messageLogList:{}", messageLogList);

        messageLogList.forEach(messageLog -> {
            if (messageLog.getTryCount() >= 3) {
                /**
                 * 重试超过3次 将消息状态置为投递失败
                 */
                messageLogMapper.changeBrokerMessageLogStatus(messageLog.getMessageId(), Constants.ORDER_SEND_FAILURE, new Date());
            } else {
                /**
                 * 重试小于3次，将消息重发
                 */
                messageLogMapper.updateReSend(messageLog.getMessageId(),new Date());
                Order order = JSON.parseObject(messageLog.getMessage(),Order.class);
                try {
                    rabbitOrderSender.send(order);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("消息重发失败！");
                }
            }
        });
        log.info("--------------定时任务结束----------------");
    }
}
